import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Switch, 
  Select, 
  InputNumber,
  Row,
  Col,
  message,
  Tabs,
  Space,
  Tag,
  Modal,
  List
} from 'antd';
import { 
  SaveOutlined,
  DeleteOutlined,
  PlusOutlined,
  FolderOpenOutlined
} from '@ant-design/icons';
import { invoke } from '@tauri-apps/api/core';
import { useSettingStore } from '../stores/settingStore';
import { useGlobalStore } from '../stores';
import { open } from '@tauri-apps/plugin-dialog';

const { Option } = Select;
const { TabPane } = Tabs;

interface ProxyConfig {
  id: string;
  host: string;
  port: number;
  username?: string;
  password?: string;
  isActive: boolean;
}

const Settings: React.FC = () => {
  const [form] = Form.useForm();
  const [proxyForm] = Form.useForm();
  const [isProxyModalVisible, setIsProxyModalVisible] = useState(false);
  const [editingProxy, setEditingProxy] = useState<ProxyConfig | null>(null);

  const { 
    settings, 
    proxies, 
    fetchSettings, 
    updateSetting, 
    fetchProxies,
    addProxy,
    updateProxy,
    deleteProxy,
    toggleProxy
  } = useSettingStore();

  const { storagePath, setStoragePath } = useGlobalStore();

  useEffect(() => {
    fetchSettings();
    fetchProxies();
  }, [fetchSettings, fetchProxies]);

  const handleSave = async (values: any) => {
    try {
      // 保存所有设置
      const settingPromises = Object.entries(values).map(([key, value]) => 
        updateSetting(key, value as string)
      );
      await Promise.all(settingPromises);
      message.success('设置保存成功');
    } catch (error) {
      message.error('设置保存失败');
    }
  };



  const handleSelectFolder = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
      });
      if (selected && typeof selected === 'string') {
        form.setFieldsValue({ storagePath: selected });
        setStoragePath(selected);
        await updateSetting('storagePath', selected);
        message.success('存储路径更新成功');
      }
    } catch (error) {
      message.error(`选择文件夹失败: ${error}`);
    }
  };

  const handleAddProxy = () => {
    setEditingProxy(null);
    proxyForm.resetFields();
    setIsProxyModalVisible(true);
  };

  const handleEditProxy = (proxy: ProxyConfig) => {
    setEditingProxy(proxy);
    proxyForm.setFieldsValue(proxy);
    setIsProxyModalVisible(true);
  };

  const handleProxyModalOk = async () => {
    try {
      const values = await proxyForm.validateFields();
      if (editingProxy) {
        await updateProxy(editingProxy.id, values);
        message.success('代理更新成功');
      } else {
        await addProxy(values);
        message.success('代理添加成功');
      }
      setIsProxyModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const GeneralSettings = () => (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSave}
      initialValues={{
        autoLogin: settings.autoLogin || 'true',
        autoSync: settings.autoSync || 'false',
        syncInterval: settings.syncInterval || '30',
        maxRetries: settings.maxRetries || '3',
        timeout: settings.timeout || '30',
        language: settings.language || 'zh_CN',
        storagePath: storagePath || '/storage'
      }}
    >
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="autoLogin"
            label="自动登录"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="autoSync"
            label="自动同步数据"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="syncInterval"
            label="同步间隔(分钟)"
          >
            <InputNumber min={1} max={1440} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="language"
            label="界面语言"
          >
            <Select>
              <Option value="zh_CN">简体中文</Option>
              <Option value="en_US">English</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="maxRetries"
            label="最大重试次数"
          >
            <InputNumber min={1} max={10} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="timeout"
            label="请求超时(秒)"
          >
            <InputNumber min={5} max={300} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="storagePath"
        label="文件存储路径"
        rules={[{ required: true, message: '请输入存储路径' }]}
      >
        <Input 
          placeholder="请输入文件存储路径"
          addonAfter={
            <Button 
              icon={<FolderOpenOutlined />}
              onClick={handleSelectFolder}
            >
              选择文件夹
            </Button>
          }
        />
      </Form.Item>

      <Form.Item>
        <Button type="primary" icon={<SaveOutlined />} htmlType="submit">
          保存设置
        </Button>
      </Form.Item>
    </Form>
  );

  const ProxySettings = () => (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddProxy}>
          添加代理
        </Button>
      </div>

      <List
        dataSource={proxies}
        renderItem={proxy => (
          <List.Item
            actions={[
              <Switch
                key="toggle"
                checked={proxy.isActive}
                onChange={() => toggleProxy(proxy.id)}
                size="small"
              />,
              <Button
                key="edit"
                type="text"
                size="small"
                onClick={() => handleEditProxy(proxy)}
              >
                编辑
              </Button>,
              <Button
                key="delete"
                type="text"
                danger
                size="small"
                onClick={() => deleteProxy(proxy.id)}
              >
                删除
              </Button>
            ]}
          >
            <List.Item.Meta
              title={`${proxy.host}:${proxy.port}`}
              description={
                <div>
                  <div>用户名: {proxy.username || '-'}</div>
                  <div>密码: {proxy.password ? '******' : '-'}</div>
                  <Tag color={proxy.isActive ? 'green' : 'red'}>
                    {proxy.isActive ? '启用' : '禁用'}
                  </Tag>
                </div>
              }
            />
          </List.Item>
        )}
      />
    </div>
  );

  const NotificationSettings = () => (
    <Form layout="vertical">
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="emailNotification"
            label="邮件通知"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="browserNotification"
            label="浏览器通知"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="notificationEmail"
        label="通知邮箱"
      >
        <Input placeholder="请输入邮箱地址" />
      </Form.Item>

      <Form.Item
        name="notificationEvents"
        label="通知事件"
      >
        <Select mode="multiple" placeholder="选择需要通知的事件">
          <Option value="task_completed">任务完成</Option>
          <Option value="task_failed">任务失败</Option>
          <Option value="account_error">账号异常</Option>
          <Option value="system_error">系统错误</Option>
        </Select>
      </Form.Item>
    </Form>
  );

  const DataSettings = () => (
    <div>
      <Card title="数据备份" style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button icon={<SaveOutlined />}>
            导出数据
          </Button>
          <Button icon={<PlusOutlined />}>
            导入数据
          </Button>
          <Button danger icon={<DeleteOutlined />}>
            清空数据
          </Button>
        </Space>
      </Card>

      <Card title="数据统计">
        <Row gutter={16}>
          <Col span={8}>
            <div>账号数量: 2</div>
          </Col>
          <Col span={8}>
            <div>任务数量: 15</div>
          </Col>
          <Col span={8}>
            <div>素材数量: 128</div>
          </Col>
        </Row>
      </Card>
    </div>
  );

  return (
    <div>
      <Card title="系统设置">
        <Tabs defaultActiveKey="general">
          <TabPane tab="常规设置" key="general">
            <GeneralSettings />
          </TabPane>
          <TabPane tab="代理设置" key="proxy">
            <ProxySettings />
          </TabPane>
          <TabPane tab="通知设置" key="notification">
            <NotificationSettings />
          </TabPane>
          <TabPane tab="数据管理" key="data">
            <DataSettings />
          </TabPane>
        </Tabs>
      </Card>

      {/* 代理编辑模态框 */}
      <Modal
        title={editingProxy ? '编辑代理' : '添加代理'}
        open={isProxyModalVisible}
        onOk={handleProxyModalOk}
        onCancel={() => setIsProxyModalVisible(false)}
        width={500}
      >
        <Form
          form={proxyForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="host"
                label="主机地址"
                rules={[{ required: true, message: '请输入主机地址' }]}
              >
                <Input placeholder="请输入主机地址" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="port"
                label="端口"
                rules={[{ required: true, message: '请输入端口' }]}
              >
                <InputNumber min={1} max={65535} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="isActive"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>


    </div>
  );
};

export default Settings; 